<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <text class="nav-title">购物车</text>
      <view class="nav-right" @click="clearCart" v-if="cartStore.cartItems.length > 0">
        <text class="clear-text">清空</text>
      </view>
    </view>
    
    <!-- 未登录状态 -->
    <view v-if="!userStore.isLoggedIn" class="empty-state">
      <image src="/static/cart-empty.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">请先登录查看购物车</text>
      <button class="login-btn" @click="goToLogin">去登录</button>
    </view>
    
    <!-- 空购物车 -->
    <view v-else-if="cartStore.cartItems.length === 0" class="empty-state">
      <image src="/static/cart-empty.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">购物车还是空的</text>
      <button class="go-shopping-btn" @click="goToHome">去购物</button>
    </view>
    
    <!-- 购物车列表 -->
    <view v-else class="cart-content">
      <!-- 店铺分组 -->
      <view class="store-section">
        <view class="store-header">
          <view class="store-info">
            <uni-icons type="shop" size="20" color="#FF8C42"></uni-icons>
            <text class="store-name">便利小店</text>
          </view>
          <view class="store-coupon" @click="viewStoreCoupons">
            <text>领券</text>
            <uni-icons type="right" size="14" color="#999"></uni-icons>
          </view>
        </view>
        
        <view class="cart-list">
          <view 
            class="cart-item" 
            v-for="(item, index) in cartStore.cartItems" 
            :key="index"
            :class="{ 'item-disabled': item.status === 0 || item.totalStock <= 0 }"
          >
            <view class="item-select">
              <checkbox 
                :key="`checkbox-${item.productId}-${item.selected}`"
                :checked="!!item.selected" 
                :disabled="item.status === 0 || item.totalStock <= 0"
                @tap="toggleSelect(item.productId, !item.selected)"
                color="#FF8C42"
              ></checkbox>
            </view>
            <view class="item-image" @click="goToDetail(item.productId)">
              <image :src="imageFullUrl(item.productImage)" mode="aspectFill"></image>
              <view class="item-tag" v-if="item.status === 0">已下架</view>
              <view class="item-tag stock-warning" v-else-if="item.totalStock <= 0">无库存</view>
              <view class="item-tag stock-warning" v-else-if="item.totalStock < item.quantity">库存不足</view>
            </view>
            <view class="item-info" @click="goToDetail(item.productId)">
              <view class="item-name">{{ item.name }}</view>
              <view class="item-specs" v-if="item.spec">{{ item.spec }}</view>
              <view class="item-price-row">
                <view class="item-price">¥{{ parseFloat(item.price).toFixed(2) }}</view>
                <view class="item-actions">
                  <view class="quantity-control">
                    <view class="quantity-btn minus" @click.stop="decreaseQuantity(item)">
                      <uni-icons type="minus" size="16" color="#999"></uni-icons>
                    </view>
                    <view class="quantity-input">{{ item.quantity }}</view>
                    <view class="quantity-btn plus" @click.stop="increaseQuantity(item)">
                      <uni-icons type="plus" size="16" color="#FF8C42"></uni-icons>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="delete-btn" @click.stop="removeItem(item.productId)">
              <uni-icons type="trash" size="20" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 优惠券区域 -->
      <view class="coupon-section">
        <view class="section-title">
          <text>优惠券</text>
        </view>
        <scroll-view scroll-x class="coupon-scroll" show-scrollbar="false">
          <view class="coupon-item coupon-new">
            <view class="coupon-left">
              <text class="coupon-value">¥10</text>
              <text class="coupon-condition">满99元可用</text>
            </view>
            <view class="coupon-right">
              <text class="coupon-name">新人专享券</text>
              <text class="coupon-time">有效期至2023-12-31</text>
              <view class="coupon-btn">立即领取</view>
            </view>
          </view>
          <view class="coupon-item coupon-discount">
            <view class="coupon-left">
              <text class="coupon-value">8.5折</text>
              <text class="coupon-condition">无门槛</text>
            </view>
            <view class="coupon-right">
              <text class="coupon-name">全场折扣券</text>
              <text class="coupon-time">有效期至2023-12-31</text>
              <view class="coupon-btn">立即领取</view>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 猜你喜欢 -->
      <view class="recommend-section">
        <view class="section-title">
          <text>猜你喜欢</text>
        </view>
        <scroll-view scroll-x class="recommend-scroll" show-scrollbar="false">
          <view 
            class="recommend-item" 
            v-for="item in recommendProducts" 
            :key="item.id"
            @click="goToDetail(item.id)"
          >
            <image :src="imageFullUrl(item.mainImageUrl)" mode="aspectFill" class="recommend-image"></image>
            <view class="recommend-name">{{ item.name }}</view>
            <view class="recommend-price">¥{{ parseFloat(item.price).toFixed(2) }}</view>
            <view class="recommend-add" @click.stop="quickAddToCart(item)">
              <uni-icons type="plus" size="18" color="#fff"></uni-icons>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 底部结算栏 - 改进版 -->
      <view class="settlement-bar">
        <view class="select-all-container">
          <checkbox 
            :checked="cartStore.isAllSelected" 
            @tap="toggleSelectAll"
            color="#FF8C42"
          ></checkbox>
          <text class="select-all-text">全选</text>
        </view>
        
        <view class="price-container">
          <view class="price-row">
            <text class="price-label">合计:</text>
            <text class="price-value">¥{{ cartStore.selectedTotalPrice }}</text>
          </view>
          <text class="discount-text">已优惠: ¥0.00</text>
        </view>
        
        <view class="buttons-container">
          <button 
            class="buy-now-btn" 
            :disabled="cartStore.selectedItemCount === 0"
            :class="{ 'btn-disabled': cartStore.selectedItemCount === 0 }"
            @click="buyNow"
          >
            立即购买
          </button>
          
          <button 
            class="checkout-btn" 
            :disabled="cartStore.selectedItemCount === 0"
            :class="{ 'btn-disabled': cartStore.selectedItemCount === 0 }"
            @click="checkout"
          >
            帮您跑腿<text v-if="cartStore.selectedItemCount > 0">({{ cartStore.selectedItemCount }})</text>
          </button>
        </view>
      </view>
    </view>
    
    <!-- 登录弹窗 -->
    <login-popup ref="loginPopupRef" @login-success="handleLoginSuccess"></login-popup>
    
    <!-- 用户类型管理 -->
    <user-type-manager></user-type-manager>
    
    <!-- 底部导航栏 -->
    <tab-bar :active="1"></tab-bar>
    <!-- 支付结果监听 -->
    <view v-if="showPaymentWebview" class="payment-webview-container">
      <web-view 
        ref="paymentWebview"
        :src="paymentUrl" 
        @message="handleWebviewMessage"
        @error="handleWebviewError"
        @load="handleWebviewLoad"
      ></web-view>
      <view class="webview-toolbar">
        <button class="toolbar-btn" @click="closePaymentWebview">关闭支付</button>
        <button class="toolbar-btn primary" @click="checkPaymentStatus">检查支付状态</button>
      </view>
    </view>
    
    <!-- 支付宝支付弹窗 -->
    <view v-if="showPaymentModal" class="payment-modal">
      <view class="payment-content">
        <view class="payment-header">
          <text class="payment-title">支付宝支付</text>
          <view class="payment-close" @click="closePaymentModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="payment-info">
          <text class="payment-amount">支付金额: ¥{{ paymentAmount.toFixed(2) }}</text>
          <text class="payment-tip">请在新打开的页面完成支付</text>
        </view>
        <view class="payment-actions">
          <button class="payment-btn" @click="openAlipayPayment">打开支付宝支付</button>
          <button class="cancel-btn" @click="cancelPayment">取消支付</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import TabBar from '@/components/tab-bar.vue';
import UserTypeManager from '@/components/user-type-manager.vue';
import LoginPopup from '@/components/login-popup.vue';
import { useUserStore } from '@/store/user';
import { useCartStore } from '@/store/cart';
import { useProductStore } from '@/store/product.js';
import { useAddressStore } from '@/store/address';
import { getImageUrl } from '@/config/env';
import { onShow } from '@dcloudio/uni-app';
import http from '@/utils/http/http.js';
import { AlipayService } from '@/utils/payment/alipay.js';
//import uni from '@dcloudio/uni-app';

// 状态栏高度
const statusBarHeight = ref(20);

// 引入用户状态管理
const userStore = useUserStore();
// 引入购物车状态管理
const cartStore = useCartStore();
// 引入商品状态管理
const productStore = useProductStore();
// 引入地址状态管理
const addressStore = useAddressStore();

// 登录弹窗引用
const loginPopupRef = ref(null);

// 推荐商品列表
const recommendProducts = ref([]);

// 支付相关数据
const showPaymentModal = ref(false);
const showPaymentWebview = ref(false);
const currentOrderNo = ref('');
const alipayFormData = ref('');
const paymentUrl = ref('');
const paymentWebview = ref(null);
const paymentAmount = ref(0);

// 生成完整的图片 URL - 使用统一的工具函数
const imageFullUrl = getImageUrl;

// 监听用户登录状态变化
watch(() => userStore.isLoggedIn, (newValue, oldValue) => {
  if (newValue && !oldValue) {
    // 用户从未登录状态变为已登录状态
    console.log('用户登录状态变化，刷新购物车数据');
    refreshCartData();
  }
});

// 刷新购物车数据
const refreshCartData = () => {
  cartStore.fetchCartList();
};

// 处理登录成功事件
const handleLoginSuccess = () => {
  console.log('登录成功，刷新购物车数据');
  refreshCartData();
};

// 获取推荐商品
const fetchRecommendProducts = () => {
  // 从商品列表中随机选择5个商品作为推荐
  const allProducts = productStore.products;
  if (allProducts && allProducts.length > 0) {
    // 过滤掉已经在购物车中的商品
    const cartProductIds = cartStore.cartItems.map(item => item.productId);
    const availableProducts = allProducts.filter(product => 
      !cartProductIds.includes(product.id) && 
      product.status !== 0 && 
      product.totalStock > 0
    );
    
    if (availableProducts.length > 0) {
      // 随机打乱数组顺序
      const shuffled = [...availableProducts].sort(() => 0.5 - Math.random());
      // 取前5个或更少
      recommendProducts.value = shuffled.slice(0, Math.min(5, shuffled.length));
    } else {
      // 如果没有可用商品，就使用所有商品
      const shuffled = [...allProducts].sort(() => 0.5 - Math.random());
      recommendProducts.value = shuffled.slice(0, Math.min(5, shuffled.length));
    }
  } else {
    // 如果没有商品数据，则获取商品列表
    fetchProducts();
  }
};

// 获取商品列表
const fetchProducts = async () => {
  try {
    await productStore.fetchProducts();
    fetchRecommendProducts();
  } catch (error) {
    console.error('获取商品列表失败:', error);
  }
};

// 快速添加到购物车
const quickAddToCart = async (product) => {
  try {
    const result = await cartStore.addToCart(product, 1);
    if (result) {
      // 更新推荐商品列表，移除已添加的商品
      fetchRecommendProducts();
    }
  } catch (error) {
    console.error('快速添加到购物车失败:', error);
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到首页
const goToHome = () => {
  uni.redirectTo({
    url: '/pages/index/index'
  });
};

// 跳转到登录页
const goToLogin = () => {
  if (loginPopupRef.value) {
    loginPopupRef.value.open();
  } else {
    uni.navigateTo({
      url: '/pages/login/index'
    });
  }
};

// 跳转到商品详情
const goToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}&t=${Date.now()}`
  });
};

// 查看店铺优惠券
const viewStoreCoupons = () => {
  uni.showToast({
    title: '优惠券功能开发中',
    icon: 'none'
  });
};

// 切换选中状态 - 使用后端接口
const toggleSelect = async (productId, selected) => {
  const currentItem = cartStore.cartItems.find(item => item.productId === productId);
  console.log('点击前状态:', {
    productId,
    currentSelected: currentItem?.selected,
    currentSelectedType: typeof currentItem?.selected,
    willSelect: selected
  });
  
  try {
    const response = await http.put('/api/cart/toggle-select', null, {
      params: {
        productId: productId,
        selected: selected
      },
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 后端更新成功，更新本地状态
      await cartStore.toggleItemSelected(productId, selected);
      
      // 强制触发响应式更新
      await nextTick();
      
      console.log('更新后状态:', {
        productId,
        newSelected: cartStore.cartItems.find(item => item.productId === productId)?.selected,
        selectedCount: cartStore.selectedItemCount,
        totalPrice: cartStore.selectedTotalPrice
      });
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('切换选中状态失败:', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 切换全选状态 - 使用后端接口
const toggleSelectAll = async () => {
  try {
    const newSelectState = !cartStore.isAllSelected;
    
    const response = await http.put('/api/cart/toggle-all-select', null, {
      params: {
        selected: newSelectState
      },
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 后端更新成功，更新本地状态
      cartStore.toggleAllSelected(newSelectState);
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('切换全选状态失败:', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 增加商品数量 - 使用后端接口
const increaseQuantity = async (item) => {
  if (item.status === 0 || item.totalStock <= 0) return;
  if (item.quantity >= (item.totalStock || 99)) {
    uni.showToast({
      title: '已达到最大库存',
      icon: 'none'
    });
    return;
  }
  
  try {
    const newQuantity = item.quantity + 1;
    
    // 调用后端更新接口
    const response = await http.put('/api/cart/update', {
      productId: item.productId,
      quantity: newQuantity
    }, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 后端更新成功，更新本地状态
      cartStore.updateCartItemQuantity(item.productId, newQuantity);
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('更新商品数量失败:', error);
    uni.showToast({
      title: '更新失败，请重试',
      icon: 'none'
    });
  }
};

// 减少商品数量 - 使用后端接口
const decreaseQuantity = async (item) => {
  if (item.status === 0 || item.totalStock <= 0) return;
  if (item.quantity <= 1) {
    uni.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          removeItem(item.productId);
        }
      }
    });
    return;
  }
  
  try {
    const newQuantity = item.quantity - 1;
    
    // 调用后端更新接口
    const response = await http.put('/api/cart/update', {
      productId: item.productId,
      quantity: newQuantity
    }, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 后端更新成功，更新本地状态
      cartStore.updateCartItemQuantity(item.productId, newQuantity);
    } else {
      uni.showToast({
        title: response.message || '更新失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('更新商品数量失败:', error);
    uni.showToast({
      title: '更新失败，请重试',
      icon: 'none'
    });
  }
};

// 删除购物车商品 - 使用后端接口
const removeItem = async (productId) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true
          });
          
          // 调用后端删除接口 - 使用DELETE方法和路径参数
          const response = await http.delete(`/api/cart/delete/${productId}`, {
            headers: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            // 后端删除成功，更新本地状态
            cartStore.removeCartItem(productId);
            // 更新推荐商品
            fetchRecommendProducts();
            
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: response.message || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除购物车商品失败:', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

// 清空购物车 - 使用后端接口
const clearCart = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '清空中...',
            mask: true
          });
          
          // 调用后端清空接口 - 使用DELETE方法
          const response = await http.delete('/api/cart/clear', {
            headers: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            // 后端清空成功，更新本地状态
            cartStore.clearCart();
            // 更新推荐商品
            fetchRecommendProducts();
            
            uni.showToast({
              title: '清空成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: response.message || '清空失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('清空购物车失败:', error);
          uni.showToast({
            title: '清空失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

// 立即购买 - 使用支付宝支付
const buyNow = async () => {
  if (cartStore.selectedItemCount === 0) {
    uni.showToast({
      title: '请选择要购买的商品',
      icon: 'none'
    });
    return;
  }
  
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    if (loginPopupRef.value) {
      loginPopupRef.value.open();
    }
    return;
  }
  
  // 显示加载中
  uni.showLoading({
    title: '处理中...',
    mask: true
  });
  
  try {
    // 获取选中的购物车商品ID列表
    const selectedCartIds = cartStore.cartItems
      .filter(item => item.selected === 1)
      .map(item => item.id)
      .filter(id => id);
    
    // 在构建订单数据前添加这一行
    await addressStore.fetchDefaultAddress();
    
    // 然后修改 orderData
    const orderData = {
      selectedCartItems: selectedCartIds,
      remark: "立即购买",
      shippingId: addressStore.getDefaultAddress?.id || addressStore.defaultAddress?.id
    };
    
    console.log('提交的订单数据:', JSON.stringify(orderData));

    paymentAmount.value = parseFloat(cartStore.selectedTotalPrice);
    
    // 发送创建订单请求 - 使用createNow接口
    const response = await http.post('/api/orders/create', orderData, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 订单创建成功
      currentOrderNo.value = response.data;
      // 清空已选中的购物车商品
      await cartStore.removeSelectedItems();
	  
      // 发起支付宝支付
      await initiateAlipayPayment(currentOrderNo.value);
     
    } else {
      uni.hideLoading();
      uni.showToast({
        title: response.message || '创建订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('立即购买失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 发起支付宝支付
const initiateAlipayPayment = async (orderNo) => {
  try {
    const paymentData = {
      orderNo: orderNo,
      paymentType: 2 // 支付宝支付
    };
    
    console.log('发起支付宝支付:', paymentData);
    
    const response = await http.post('/api/orders/pay', paymentData, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data && response.data.payUrl) {
      // 保存支付表单数据
      alipayFormData.value = response.data.payUrl;
      
      // 显示支付弹窗
      showPaymentModal.value = true;
      uni.hideLoading();
      
      console.log('支付宝支付请求成功');
    } else {
      uni.hideLoading();
      uni.showToast({
        title: response.message || '发起支付失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('发起支付宝支付失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: '发起支付失败，请重试',
      icon: 'none'
    });
  }
};

// 打开支付宝支付页面
const openAlipayPayment = async () => {
  try {
    if (!alipayFormData.value) {
      uni.showToast({
        title: '支付数据异常',
        icon: 'none'
      });
      return;
    }

    // 关闭支付弹窗
    showPaymentModal.value = false;

    // #ifdef MP-WEIXIN
    // 微信小程序中，复制支付链接
    uni.setClipboardData({
      data: alipayFormData.value,
      success: () => {
        uni.showModal({
          title: '支付提示',
          content: '支付链接已复制，请在浏览器中打开完成支付',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
    // #endif
    
    // #ifdef H5
    // H5环境中，直接打开新窗口
    const payWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
    if (payWindow) {
      payWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>支付宝支付</title>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <\/head>
        <body>
          <div style="text-align: center; padding: 20px;">
            <h3>正在跳转到支付宝支付页面...</h3>
            <p>如果没有自动跳转，请点击下方按钮</p>
          <\/div>
          ${alipayFormData.value}
          <script>
            // 自动提交表单
            setTimeout(() => {
              const form = document.querySelector('form');
              if (form) {
                form.submit();
              }
            }, 1000);
          <\/script>
        <\/body>
        <\/html>
      `);
      payWindow.document.close();
    }
    // #endif
    
    // #ifdef APP-PLUS
    // App环境中使用浏览器支付方案
    await handleAppAlipayPayment();
    // #endif
    
    // 跳转到支付结果页面
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
      });
    }, 2000);
    
  } catch (error) {
    console.error('打开支付宝支付页面失败:', error);
    uni.showToast({
      title: '打开支付页面失败',
      icon: 'none'
    });
  }
};

// App环境中的支付宝支付处理
const handleAppAlipayPayment = async () => {
  try {
    console.log('使用浏览器支付方案');
    
    // 直接使用浏览器支付，不再尝试原生调用
    const alipayService = new AlipayService();
    const result = await alipayService.pay(alipayFormData.value);
    handlePaymentResult(result);
    
  } catch (error) {
    console.error('浏览器支付失败:', error);
    
    // 显示用户友好的错误信息
    uni.showModal({
      title: '支付提示',
      content: '无法打开支付页面，请检查设备是否安装浏览器应用',
      showCancel: true,
      cancelText: '取消',
      confirmText: '重试',
      success: (res) => {
        if (res.confirm) {
          // 重试支付
          handleAppAlipayPayment();
        } else {
          // 取消支付
          cancelPayment();
        }
      }
    });
  }
};

// 处理WebView消息
const handleWebviewMessage = (event) => {
  console.log('WebView消息:', event.detail.data);
  const data = event.detail.data[0];
  
  if (data.action === 'checkPayment') {
    checkPaymentStatus();
  }
};

// 处理WebView错误
const handleWebviewError = (error) => {
  console.error('WebView错误:', error);
  uni.showToast({
    title: '支付页面加载失败',
    icon: 'none'
  });
};

// 处理WebView加载完成
const handleWebviewLoad = () => {
  console.log('WebView加载完成');
};

// 关闭支付WebView
const closePaymentWebview = () => {
  showPaymentWebview.value = false;
  paymentUrl.value = '';
};

// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    const response = await http.get(`/api/orders/payment-status/${currentOrderNo.value}`, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      const paymentStatus = response.data.status;
      
      if (paymentStatus === 'SUCCESS') {
        closePaymentWebview();
        await handlePaymentSuccess();
      } else if (paymentStatus === 'FAILED') {
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        });
      } else {
        uni.showToast({
          title: '支付状态确认中...',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('检查支付状态失败:', error);
    uni.showToast({
      title: '检查支付状态失败',
      icon: 'none'
    });
  }
};

// 处理支付结果
const handlePaymentResult = async (result) => {
  console.log('支付结果:', result);
  
  if (result.resultStatus === '9000') {
    // Payment successful
    await handlePaymentSuccess();
  } else if (result.resultStatus === '6001') {
    // 用户取消支付
    uni.showToast({
      title: '支付已取消',
      icon: 'none'
    });
  } else {
    // 支付失败
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    });
  }
};

// 处理支付成功
const handlePaymentSuccess = async () => {
  try {
    // Get selected cart item IDs for backend deletion
    const selectedCartIds = cartStore.cartItems
      .filter(item => item.selected === 1)
      .map(item => item.id)
      .filter(id => id);
    
    // Call backend API to delete selected items
    if (selectedCartIds.length > 0) {
      const response = await http.delete('/api/cart/delete-selected', {
        data: { cartIds: selectedCartIds },
        headers: {
          'Authorization': `Bearer ${userStore.token}`
        }
      });
      
      if (response.code === 200) {
        // Backend deletion successful, update local state
        cartStore.removeSelectedItems();
      }
    }
    
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    });
    
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
      });
    }, 1500);
  } catch (error) {
    console.error('处理支付成功失败:', error);
    // Even if cart cleanup fails, still redirect to success page
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
      });
    }, 1500);
  }
};

// 取消支付
const cancelPayment = () => {
  showPaymentModal.value = false;
  uni.showToast({
    title: '支付已取消',
    icon: 'none'
  });
  // Don't redirect, just stay on current page
};

// 结算
const checkout = () => {
  if (cartStore.selectedItemCount === 0) {
    uni.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    });
    return;
  }
  
  // 获取选中的商品数据
  const selectedItems = cartStore.cartItems.filter(item => item.selected === 1).map(item => ({
    id: item.productId,
    name: item.name,
    image: item.mainImageUrl,
    price: parseFloat(item.price),
    number: item.quantity
  }));
  
  // 将选中的商品数据传递到结算页面
  uni.navigateTo({
    url: `/pages/orders/checkout`
  });
};

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = `${systemInfo.statusBarHeight || 20}px`;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = '20px';
  }
};
// 获取默认地址
const fetchDefaultAddress = async () => {
  try {
    await addressStore.fetchDefaultAddress();
    if (addressStore.defaultAddress) {
      selectedAddress.value = {
        id: addressStore.defaultAddress.id,
        receiverName: addressStore.defaultAddress.receiverName,
        receiverPhone: addressStore.defaultAddress.receiverPhone,
        receiverProvince: addressStore.defaultAddress.province,
        receiverCity: addressStore.defaultAddress.city,
        receiverDistrict: addressStore.defaultAddress.district,
        receiverAddress: addressStore.defaultAddress.detailAddress,
        isDefault: addressStore.defaultAddress.isDefault
      };
    }
  } catch (error) {
    console.error('获取默认地址失败:', error);
  }
};

// 生命周期钩子
onMounted(() => {
  console.log('购物车页面已挂载');
  // 获取状态栏高度
  getStatusBarHeight();
  // 初始化用户状态
  userStore.initUserState();
  // 获取购物车列表
  cartStore.fetchCartList();
  // 获取推荐商品
  fetchRecommendProducts();
});

// 每次显示页面时刷新数据
onShow(() => {
  console.log('购物车页面显示，重新初始化用户状态');
  // 重新初始化用户状态，确保从其他页面跳转回来时能正确获取登录状态
  userStore.initUserState();
  // 刷新购物车数据
  cartStore.fetchCartList();
  // 刷新推荐商品
  fetchRecommendProducts();
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  position: relative;
  z-index: 100;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.clear-text {
  font-size: 26rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.login-btn, .go-shopping-btn {
  width: 280rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
  transition: all 0.3s ease;
}

.login-btn:active, .go-shopping-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 66, 0.2);
}

/* 购物车内容 */
.cart-content {
  padding-bottom: 120rpx;
}

/* 店铺分组 */
.store-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.store-info {
  display: flex;
  align-items: center;
}

.store-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}

.store-coupon {
  display: flex;
  align-items: center;
  background-color: #FFF0E0;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.store-coupon text {
  font-size: 22rpx;
  color: #FF8C42;
  margin-right: 6rpx;
}

/* 购物车列表 */
.cart-list {
  padding: 10rpx 0;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  position: relative;
  border-bottom: 1rpx solid #FFE6CC;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-disabled {
  opacity: 0.6;
}

.item-select {
  margin-right: 20rpx;
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  position: relative;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.item-image image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.item-tag {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(153, 153, 153, 0.8);
  color: white;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 0 0 8rpx 0;
}

.stock-warning {
  background-color: rgba(255, 159, 28, 0.8);
}

.item-info {
  flex: 1;
  margin-right: 20rpx;
  position: relative;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-specs {
  font-size: 24rpx;
  color: #999;
  background-color: #FFF0E0;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  display: inline-block;
  margin-bottom: 16rpx;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 32rpx;
  color: #FF8C42;
  font-weight: bold;
}

.item-actions {
  display: flex;
  align-items: center;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1rpx solid #FFE6CC;
  border-radius: 8rpx;
  overflow: hidden;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFF9F2;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  border-left: 1rpx solid #FFE6CC;
  border-right: 1rpx solid #FFE6CC;
}

.delete-btn {
  position: absolute;
  top: 20rpx;
  right: 30rpx;
  padding: 10rpx;
}

/* 优惠券区域 */
.coupon-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.coupon-scroll {
  white-space: nowrap;
  padding: 10rpx 0;
}

.coupon-item {
  display: inline-flex;
  width: 500rpx;
  height: 180rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.coupon-new {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
}

.coupon-discount {
  background: linear-gradient(to right, #4A90E2, #5CB3FF);
}

.coupon-left {
  width: 180rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  position: relative;
}

.coupon-left::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 4rpx;
  background-color: rgba(255, 255, 255, 0.3);
}

.coupon-value {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.coupon-condition {
  font-size: 22rpx;
  opacity: 0.8;
}

.coupon-right {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.coupon-name {
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.coupon-time {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20rpx;
}

.coupon-btn {
  display: inline-block;
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  font-size: 24rpx;
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  align-self: flex-start;
}

/* 猜你喜欢 */
.recommend-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42;
  border-radius: 3rpx;
}

.recommend-scroll {
  white-space: nowrap;
  padding: 10rpx 0;
}

.recommend-item {
  display: inline-block;
  width: 200rpx;
  margin-right: 20rpx;
  position: relative;
}

.recommend-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
  margin-bottom: 10rpx;
}

.recommend-name {
  font-size: 24rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6rpx;
}

.recommend-price {
  font-size: 26rpx;
  color: #FF8C42;
  font-weight: bold;
}

.recommend-add {
  position: absolute;
  right: 10rpx;
  bottom: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #FF8C42;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 66, 0.3);
}

/* 结算栏 - 改进版 */
.settlement-bar {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  right: 0;
  height: 110rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border-top: 1rpx solid #FFE6CC;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 全选区域 */
.select-all-container {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
  min-width: 120rpx;
}

.select-all-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 10rpx;
}

/* 价格区域 */
.price-container {
  flex: 1;
  padding: 0 15rpx;
}

.price-row {
  display: flex;
  align-items: baseline;
}

.price-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.price-value {
  font-size: 36rpx;
  color: #FF8C42;
  font-weight: bold;
}

.discount-text {
  font-size: 22rpx;
  color: #999;
  margin-top: 6rpx;
}

/* 按钮区域 */
.buttons-container {
  display: flex;
  gap: 15rpx;
}

/* 立即购买按钮 */
.buy-now-btn {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 25rpx;
  background: linear-gradient(135deg, #FF9800, #F57C00);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(245, 124, 0, 0.3);
  transition: all 0.3s ease;
}

.buy-now-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(245, 124, 0, 0.2);
}

/* 帮您跑腿按钮 */
.checkout-btn {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 25rpx;
  background: linear-gradient(135deg, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
  transition: all 0.3s ease;
}

.checkout-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 66, 0.2);
}

.btn-disabled {
  background: linear-gradient(to right, #CCCCCC, #DDDDDD);
  box-shadow: none;
  opacity: 0.8;
}

/* 响应式调整 */
@media screen and (max-width: 375px) {
  .settlement-bar {
    padding: 0 10rpx;
  }
  
  .buy-now-btn, .checkout-btn {
    padding: 0 15rpx;
    font-size: 26rpx;
  }
}

/* 支付弹窗样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.payment-content {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin: 40rpx;
  max-width: 600rpx;
  width: 100%;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.payment-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.payment-close {
  padding: 10rpx;
}

.payment-info {
  text-align: center;
  margin-bottom: 40rpx;
}

.payment-amount {
  display: block;
  font-size: 36rpx;
  color: #FF8C42;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.payment-tip {
  display: block;
  font-size: 26rpx;
  color: #666;
}

.payment-actions {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.payment-btn {
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #1677ff, #40a9ff);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: none;
}

.cancel-btn {
  height: 80rpx;
  line-height: 80rpx;
  background-color: #f5f5f5;
  color: #666;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: none;
}

/* WebView支付容器 */
.payment-webview-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 10000;
}

.webview-toolbar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.toolbar-btn {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
  border: 1rpx solid #ddd;
  background-color: #fff;
  color: #666;
}

.toolbar-btn.primary {
  background: linear-gradient(to right, #1677ff, #40a9ff);
  color: #fff;
  border: none;
}
</style>
